<?php

require_once('ZNF/Business/DB.php');
require_once('ZNF/Util/Utility.php');
require_once('LinksDAO.php');
require_once('ccurl.php');
require_once('cpr.php');


class Backlinks_Business_backlinksDAO
{
    private $_db = null,
		    $backlink_id = null;
	    
	public function __construct() {
				$this->_db = ZNF_Business_DB::getInstance();
	}
	    
	public function getUsersWithbacklinks() {
		
	
	$sql = "SELECT * FROM t_users JOIN t_backlinks USING (user_id) WHERE bl_id = 1 AND backlink_started < DATE_SUB(CURDATE(), INTERVAL 5 DAY) GROUP BY user_id";
	$data = $this->_db->getAll($sql);
	return $data;
	}
 
	public function sendNotifications($user) {
		$eol = "\n";
		$headers = 'From: Todo system administrator<eimantas@enigmasoftware.com>'.$eol;
		$headers .= "Message-ID: <".$now." TheSystem@enigmasoftware.com>".$eol;
		$headers .= "X-Mailer: PHP v".phpversion().$eol;          
		$mime_boundary = md5(time());
		$headers .= 'MIME-Version: 1.0'.$eol;
		$headers .= "Content-Type: multipart/alternative; boundary=\"".$mime_boundary."\"".$eol.$eol;
		$msg = "";
		# Text Version
		$msg .= "--".$mime_boundary.$eol;
		$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
		$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
		$msg .= "Update mail client to see more information".$eol;
		$msg .= "--".$mime_boundary.$eol;
		$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
		$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;


		$sql = "SELECT * FROM t_projects JOIN t_backlinks USING (project_id) WHERE bl_id = 1 AND backlink_started < DATE_SUB(CURDATE(), INTERVAL 5 DAY) AND user_id = '$user[user_id]'";
		$data = $this->_db->getAll($sql);
		for ($i=0; $i<count($data); $i++) {
			$dologin = base64_encode($user['user_password'] ^ $data[$i]['backlink_started']);
			$msg .= "<b>Project: </b>".$data[$i][project_url]."<br />".$eol;
			$msg .= "<b>Added on: </b>".$data[$i][backlink_started]."<br />".$eol;
			$msg .= "<b>backlink: </b>".nl2br(stripcslashes($data[$i]['backlink_description']))."<br />".$eol;
			$msg .= "<b>Notes: </b>".nl2br(stripcslashes($data[$i]['backlink_comments']))."<br />".$eol;
			$msg .= "<b>backlink Details: </b><a href='localhost/todo/index.php?module=backlinks&action=view&backlink_id=".$data[$i]['backlink_id']."&dologin=$dologin'>localhost/todo/index.php?module=backlinks&action=view&backlink_id=".$data[$i]['backlink_id']."</a><br /><br /><hr />".$eol.$eol;
		}
		$msg .= "--".$mime_boundary."--".$eol;
		mail($user['user_email'], 'Notification', $msg, $headers);

	}
    
	public function loginForbacklink($backlink_id, $auth) {
		$_SESSION['znf']['admin'] = 1;
		$backlink = $this->getbacklinkDetails($backlink_id);
		$sql = "SELECT * FROM t_users WHERE user_id = '$backlink[user_id]'";
		$user = $this->_db->getRow($sql);
		$_SESSION['znf']['admin'] = 0;
		$dologin = base64_encode($user['user_password'] ^ $backlink['backlink_started']);
		if ($dologin == $auth) {
			$sql = "UPDATE t_users SET last_login = NOW() WHERE user_id = '$user[user_id]'";
			$this->_db->query($sql);
			$_SESSION['znf']['username'] = $user['user_login'];
			$_SESSION['znf']['userdetails'] = $user['user_details'];
			$_SESSION['znf']['user_id'] = $user['user_id'];
			$_SESSION['znf']['roles'] = $user['user_superuser']?"admin":"user";
			$_SESSION['znf']['admin'] = $user['user_admin']?2:$user['user_superuser'];
			$_SESSION['znf']['company_id'] = $user['company_id'];
			$_SESSION['znf']['theme'] = ($user['template'] && $user['template'] != 'default')?$user['template']:'enigma';
			$_SESSION['znf']['companies'] = null;
			$_SESSION['js_message'] = md5($user['user_login']) == $user['user_password']?'Pleas change your Password':'';
		}
        }
    
	public function getMyBacklinks($user_id = 0, $start=0, $end=0, $where='') {
		$seperetor = '';
		
		if(isset($start))
			
			$separator = "AND date_added >= '$start' AND date_added < '$end'";
			
		if($where){
			foreach($where as $field => $value)
		    	$separator .= "AND $field like '%$value%'";
		}
//		var_dump($separator);
		$sql = "SELECT t_backlinks.*, cache.*, t_projects.*, bi.*,  t_backlink_type.bl_type_name as backlink_type, t_users.user_login 
				FROM t_backlinks JOIN t_projects USING (project_id) 
		JOIN t_users  USING (user_id) 
		LEFT JOIN t_backlink_info as bi USING (bl_info_id) 
		LEFT JOIN t_backlink_type ON t_backlinks.bl_id = t_backlink_type.bl_type_id
		LEFT JOIN t_backlink_cache_history as cache ON t_backlinks.bl_id = cache.bl_cache_id
			WHERE (t_backlinks.user_id = $user_id OR (t_backlinks.user_id IS NULL) 
					AND t_backlinks.project_id IN (SELECT project_id FROM t_user_project WHERE t_user_project.user_id = $user_id))
					$separator
			ORDER BY t_backlinks.user_id ASC, bl_id ASC";
		
//		logg($sql);
			
		$data = $this->_db->getAll($sql);
		return $data;
	}
	
	public function getAddedBacklinks($user_id = 0) {
		$sql = "SELECT * FROM t_backlinks JOIN t_projects USING (project_id) 
		JOIN t_users USING (user_id) WHERE user_id = $user_id AND user_id <> $user_id
		ORDER BY bl_id DESC";
		return $this->_db->getAll($sql);
	}
	
	public function getPendingbacklinks($user_id = 0) {

		if ($_SESSION['znf']['admin']) $sql = "SELECT t_users.*, t_backlinks.*, assigner.user_login as assigner_login, assigner.user_details as assigner, assigner.user_id as assigner_id FROM t_backlinks JOIN t_users USING (user_id) JOIN t_users as assigner ON t_backlinks.user_id = assigner.user_id ";
		else $sql = "SELECT t_users.*, t_backlinks.*, assigner.user_login as assigner_login, assigner.user_details as assigner, assigner.user_id as assigner_id FROM t_users JOIN t_user_project USING (user_id) JOIN t_backlinks USING (user_id) JOIN t_users as assigner ON t_backlinks.user_id = assigner.user_id WHERE backlink_state = 2 AND project_id IN (SELECT project_id FROM t_user_project WHERE user_id = '$user_id' AND user_lead = 1) ORDER BY bl_id DESC";
		return $this->_db->getAll($sql);
	}
	
	public function Aprove($backlink_id = 0) {
		if ($_SESSION['znf']['admin']) $sql = "UPDATE t_backlinks SET backlink_state = 0 WHERE backlink_id = $backlink_id";
		else $sql = "UPDATE t_backlinks SET backlink_state = 0 WHERE backlink_id = $backlink_id AND project_id IN (SELECT project_id FROM t_user_project WHERE user_id = '".$_SESSION['znf']['user_id']."' AND user_lead = 1)";
		$this->_db->query($sql);
	}

	public function Dismis($backlink_id = 0) {
		if ($_SESSION['znf']['admin']) 
			$sql = "DELETE FROM t_backlinks WHERE bl_id = $backlink_id";
		else $sql = "DELETE FROM t_backlinks WHERE bl_id = $backlink_id AND (user_id = ".$_SESSION['znf']['user_id']." OR project_id IN (SELECT project_id FROM t_user_project WHERE user_id = '".$_SESSION['znf']['user_id']."' AND user_lead = 1))";
		$this->_db->query($sql);
		
		$sql = "DELETE FROM t_backlink_info WHERE bl_info_id = $backlink_id";
		$this->_db->query($sql);
		
		$sql = "DELETE FROM t_backlink_cache_history WHERE bl_cache_id = $backlink_id";
		$this->_db->query($sql);
		
		if($_POST['bl_cost_id']){
			$sql = "DELETE FROM t_backlink_costs WHERE bl_cost_id = $_POST[bl_cost_id]";
			$this->_db->query($sql);
		}
	}
	

	
/**
 *  Gets project details 
 * 
 * @param unknown_type $user_id
 * @return projects
 */
 


	public function getProjects($user_id = 0) {
		$sql = "SELECT * FROM t_projects JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE father_id = 0 ORDER BY t_projects.project_url";
		$data = $this->_db->GetAll($sql);
		$projects = array();
		for ($i=0; $i<count($data); $i++) {
			if ($_SESSION['znf']['admin']) 
			$sql = "SELECT t_projects.*, SUM(bl_id) AS open_backlinks, COUNT(bl_id) AS total_backlinks FROM t_projects 
			LEFT JOIN t_backlinks ON t_backlinks.project_id = t_projects.project_id			
			JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE t_projects.project_id = '".$data[$i]['project_id']."' GROUP BY t_projects.project_id ORDER BY project_url ASC";
			
			else $sql = "SELECT t_projects.*, SUM(bl_id) AS open_backlinks, COUNT(bl_id) AS total_backlinks FROM t_projects JOIN t_user_project ON t_projects.project_id = t_user_project.project_id LEFT JOIN t_backlinks ON t_projects.project_id = t_backlinks.project_id AND (t_backlinks.project_id IN (SELECT project_id FROM t_user_project WHERE t_user_project.user_id = $user_id AND user_lead = 1) OR t_backlinks.user_id = $user_id) JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE t_user_project.user_id = $user_id AND t_projects.project_id = '".$data[$i]['project_id']."' GROUP BY t_projects.project_id ORDER BY project_url ASC";
			$project = $this->_db->GetRow($sql);
			
			if ($project) array_push($projects, $project);
			if ($_SESSION['znf']['admin']) $sql = "SELECT t_projects.*, SUM(bl_id) AS open_backlinks, COUNT(bl_id) AS total_backlinks FROM t_projects LEFT JOIN t_backlinks ON t_backlinks.project_id = t_projects.project_id JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE father_id = '".$data[$i]['project_id']."' GROUP BY t_projects.project_id ORDER BY project_url ASC";
			else $sql = "SELECT t_projects.*, SUM(bl_id) AS open_backlinks, COUNT(bl_id) AS total_backlinks FROM t_projects JOIN t_user_project ON t_projects.project_id = t_user_project.project_id LEFT JOIN t_backlinks ON t_projects.project_id = t_backlinks.project_id  AND (t_backlinks.project_id IN (SELECT project_id FROM t_user_project WHERE t_user_project.user_id = $user_id AND user_lead = 1) OR t_backlinks.user_id = $user_id) JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE t_user_project.user_id = $user_id AND father_id = '".$data[$i]['project_id']."'  GROUP BY t_projects.project_id ORDER BY project_url ASC";
			$sub_data = $this->_db->GetAll($sql);
			if (!$project && $sub_data) {
				$project = $data[$i];
				$project['total_backlinks'] = 0;
				$project['open_backlinks'] = 0;
				array_push($projects, $project);
			}
			for ($j=0; $j<count($sub_data); $j++) {
				$sub_data[$j]['project_url'] = '&nbsp;&nbsp;&nbsp;&nbsp;'.$sub_data[$j]['project_url'];
				array_push($projects, $sub_data[$j]);
			}
		}
		
		return $projects; 
	}
	
	public function getProjectbacklinks($user_id, $project_id = 0, $open = 2) {
		
		if ($_SESSION['znf']['admin']) 
			$sql = "SELECT t_users.*, t_backlink_info.*,  t_backlink_type.bl_type_name as backlink_type FROM t_backlinks 
			JOIN t_users USING (user_id) 
			LEFT JOIN t_backlink_info ON t_backlinks.bl_id = t_backlink_info.bl_info_id 
			LEFT JOIN t_backlink_type ON t_backlinks.bl_id = t_backlink_type.bl_type_id 
			LEFT JOIN t_backlink_cache_history as cache ON t_backlinks.bl_id = cache.bl_cache_id 
			WHERE project_id = '$project_id' $add ORDER BY bl_id DESC";
			
		else $sql = "SELECT t_users.*, t_backlink_info.*, t_backlink_type.bl_type_name as backlink_type, cache.* FROM t_backlinks 
		JOIN t_users USING (user_id) 
		LEFT JOIN t_backlink_info ON t_backlinks.bl_id = t_backlink_info.bl_info_id 
		LEFT JOIN t_backlink_type ON t_backlinks.bl_id = t_backlink_type.bl_type_id 
		LEFT JOIN t_backlink_cache_history as cache ON t_backlinks.bl_id = cache.bl_cache_id
		WHERE (project_id IN (SELECT project_id FROM t_user_project WHERE user_id = $user_id AND user_lead = 1) OR t_users.user_id = $user_id) AND
		 project_id = '$project_id' $add
		 ORDER BY bl_name, bl_id DESC";

		return $this->_db->getAll($sql);
	}

	public function getSellers() {
		$sql = "SELECT * FROM t_sellers ORDER BY seller_name ASC";
		return $this->_db->getAll($sql);
	}
	
	public function addSeller($seller) {
		$seller = addslashes($seller);
		$sql = "SELECT COUNT(*) FROM t_sellers WHERE seller_name = '$seller'";
		if (!$this->_db->getOne($sql)) $this->_db->query("INSERT INTO t_sellers (seller_name) VALUES ('$seller')");
	}
	
	public function getWorkers($user_id = 0) {
		if ($_SESSION['znf']['admin']) 
		$sql = "SELECT t_users.*, t_department.*, SUM(bl_id) AS open_backlinks, COUNT(bl_id) AS total_backlinks FROM t_users LEFT JOIN t_department USING (department_id) LEFT JOIN t_backlinks ON t_backlinks.user_id = t_users.user_id 
		JOIN t_user_company ON t_users.user_id = t_user_company.user_id AND t_user_company.company_id = ".$_SESSION['znf']['company_id']." GROUP BY t_users.user_id ORDER BY department_name ASC, user_login ASC";
		
		else $sql = "SELECT t_users.*, t_department.*, SUM(bl_id) AS open_backlinks, COUNT(bl_id) AS total_backlinks FROM t_users LEFT JOIN t_department USING (department_id) LEFT JOIN t_backlinks ON t_users.user_id = t_backlinks.user_id AND (t_backlinks.project_id IN (SELECT tmp.project_id FROM t_user_project as tmp WHERE tmp.user_id = $user_id AND user_lead = 1) OR t_backlinks.user_id = $user_id) 
		JOIN t_user_company ON t_users.user_id = t_user_company.user_id AND t_user_company.company_id = ".$_SESSION['znf']['company_id']." WHERE t_users.user_id IN (SELECT user_id FROM t_user_project WHERE project_id IN (SELECT tmp.project_id FROM t_user_project as tmp WHERE tmp.user_id = $user_id)) GROUP BY t_users.user_id ORDER BY department_name ASC, user_login ASC";
		return $this->_db->getAll($sql);
	}

	public function getWorkerBacklinks($lead_id = 0, $user_id = 0, $open = 2) {
		

		if ($_SESSION['znf']['admin']) $sql = "SELECT t_users.*, t_backlinks.*, assigner.user_login as assigner_login, assigner.user_details as assigner, assigner.user_id as assigner_id FROM t_users JOIN t_backlinks USING (user_id) JOIN t_users as assigner ON t_backlinks.user_id = assigner.user_id WHERE t_users.user_id = '$user_id' $add ORDER BY bl_id DESC";
		else $sql = "SELECT t_users.*, t_backlinks.*, assigner.user_login as assigner_login, assigner.user_details as assigner, assigner.user_id as assigner_id 
		FROM t_users JOIN t_backlinks USING (user_id) 
		JOIN t_users as assigner ON t_backlinks.user_id = assigner.user_id 
		WHERE (project_id IN (SELECT project_id FROM t_user_project 
		WHERE user_id = '$lead_id' AND user_lead = 1) OR t_users.user_id = $lead_id) AND t_users.user_id = '$user_id'  ORDER BY bl_id DESC";
		return $this->_db->getAll($sql);
	}
	
/**
 * Gets backlinks details
 *
 * @param int $backlink_id
 * @return details arrays
 */
	public function getBacklinkDetails($backlink_id = 0) {
		
		if ($_SESSION['znf']['admin']) $sql = "SELECT * FROM t_backlinks 
				JOIN t_projects USING (project_id)				
				LEFT JOIN t_backlink_info USING (bl_info_id)
				LEFT JOIN t_backlink_type USING (bl_type_id)
				LEFT JOIN t_backlink_costs ON (t_backlinks.cost_id = t_backlink_costs.bl_cost_id)
				WHERE bl_id = '$backlink_id'";
				
		else $sql = "SELECT * FROM t_backlinks JOIN t_projects USING (project_id) 
				LEFT JOIN t_backlink_info USING (bl_info_id)
				LEFT JOIN t_backlink_type USING (bl_type_id)
				LEFT JOIN t_backlink_costs ON (t_backlinks.cost_id = t_backlink_costs.bl_cost_id)
				WHERE bl_id = '$backlink_id' AND (user_id = ".$_SESSION['znf']['user_id']." OR user_id = ".$_SESSION['znf']['user_id']." 
						OR project_id IN (SELECT project_id FROM t_user_project WHERE user_id = ".$_SESSION['znf']['user_id']."
						AND user_lead = 1) OR user_id IS NULL)";
		return $this->_db->getRow($sql);  
	}

/**
 * Gets projects workers
 *
 * @param int $project_id
 * @return unknown
 */
	public function getProjectWorkers($project_id) {
		$sql = "SELECT * FROM t_users JOIN t_user_project USING (user_id) WHERE project_id = '$project_id' AND user_reporter = 0 ORDER BY user_login ASC";
		$data = $this->_db->getAll($sql);
		array_push($data, array('user_id' => 'NULL', 'user_login' => 'Anyone'));
		return $data;
	}
	
	public function getWorkerProjects($user_id) {
		
		if ($user_id) {
			if ($_SESSION['znf']['admin']) $sql = "SELECT * FROM t_projects JOIN t_user_project USING (project_id) JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE user_id = '$user_id' AND user_reporter = 0 ORDER BY project_url ASC";
			else $sql = "SELECT * FROM t_projects JOIN t_user_project USING (project_id) JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE user_id = '$user_id' AND user_reporter = 0 AND t_projects.project_id IN (SELECT project_id FROM t_user_project WHERE t_user_project.user_id = ".$_SESSION['znf']['user_id'].") ORDER BY project_url ASC"; 
			return $this->_db->getAll($sql);
		} else {
			if ($_SESSION['znf']['admin']) {
				$sql = "SELECT * FROM t_projects JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE father_id = 0 ORDER BY t_projects.project_url";
				$data = $this->_db->GetAll($sql);
				$projects = array();
				for ($i=0; $i<count($data); $i++) {
					array_push($projects, $data[$i]);
					$sql = "SELECT * FROM t_projects JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE father_id = '".$data[$i]['project_id']."' ORDER BY t_projects.project_url";
					$sub_data = $this->_db->GetAll($sql);
					for ($j=0; $j<count($sub_data); $j++) {
						$sub_data[$j]['project_url'] = '&nbsp;&nbsp;&nbsp;&nbsp;'.$sub_data[$j]['project_url'];
						array_push($projects, $sub_data[$j]);
					}
				}
				return $projects;
			}
			else {
				$sql = "SELECT * FROM t_projects JOIN t_user_project USING (project_id) JOIN t_project_company ON t_projects.project_id = t_project_company.project_id AND t_project_company.company_id = ".$_SESSION['znf']['company_id']." WHERE user_id = ".$_SESSION['znf']['user_id']." ORDER BY project_url ASC";
				return $this->_db->getAll($sql);
			} 
		}
	}

	public function getProjectName($project_id) {
		$sql = "SELECT project_url FROM t_projects WHERE project_id = $project_id";
		return $this->_db->getOne($sql);
	}
    
	public function getWorkerName($user_id) {
		$sql = "SELECT user_login FROM t_users WHERE user_id = $user_id";
		return $this->_db->getOne($sql);
	}
	
/**
 * Insets backlink
 *
 */
	public function addBacklink($reciprocal_url) {
		
		ZNF_Util_Utility :: addAllSlashes($reciprocal_url);
		$url = substr($_POST['bl_url'],7); 								//$url = 'http://localhost/todo/backlinks/Business/string.php';
		
//        if(!is_integer($_GET['user_id']))
//			return $_SESSION['znf']['message'] = "Wrong user id";

		$backlink = $this->scanBacklink($url, $reciprocal_url);

		
		//--- t_backlinks_info

		$sql = "INSERT INTO t_backlink_info (
					bl_info_id,
					bl_url,
					bl_name,
					date_added,
					last_check_date,
					PR,
					OBL,
					flag
					)
					VALUES (
					NULL, '$_POST[bl_url]', '".addslashes($backlink->bl_name)."', NOW() , NOW(), $backlink->PR, $backlink->OBL, '$backlink->flag'
					);";

$sqla[0] = $sql;
					
		if($this->_db->query($sql))		

			if($_POST['cost']){
				$sql = "INSERT INTO t_backlink_costs (
					`bl_cost_id` , 
					`from_date` ,
					`to_date` ,
					`cost` ,
					`currency` ,
					`type`,
					reciprocal_url
					)
					VALUES (
					NULL, '$_POST[from_date]', '$_POST[to_date]', $_POST[cost], '$_POST[currency]', '$_POST[type]', '$_POST[reciprocal_url]')";
				
		
				$this->bl_cost_id = $this->_db->getOne("SELECT bl_cost_id FROM t_backlink_costs order by bl_cost_id desc LIMIT 1");
			}
		
$sqla[1] = $sql;		
	
			$this->bl_info_id = $this->_db->getOne("SELECT bl_info_id FROM t_backlink_info order by bl_info_id desc LIMIT 1");

			$sql = "INSERT INTO t_backlinks (
			`bl_id` ,
			`bl_info_id` ,
			`cost_id` ,
			`bl_type_id` ,
			`bl_lng_id` ,
			`project_id`,
			`user_id`			
			)
			VALUES (
			NULL,
			'$this->bl_info_id',
			'$this->bl_cost_id',
			'$_POST[bl_type_id]',
			'$_POST[bl_lng_id]',
			'$_POST[project_id]',
			'" .$_GET['user_id']."' 	
			)";
			

		$this->_db->query($sql);	$sqla[2] = $sql;
	
		//--	cache	
		
		$sql = "INSERT INTO t_backlink_cache_history ( bl_cache_id , google_date, yahoo_date, msn_date )
											  VALUES ('$this->bl_info_id', '$backlink->GoogleCacheDate', '$backlink->YahooCacheDate', '$backlink->MsnCacheDate')";
		$this->_db->query($sql);
		

//		$sqla[3] = $sql;		$this->s$sqla,0);

												  		
		
	}

	public function sendEmail($email) {
		$backlink = $this->getbacklinkDetails($this->backlink_id);
				
		$sql = "SELECT * FROM t_users WHERE user_id = '$backlink[user_id]'";
		$user = $this->_db->getRow($sql);
		$dologin = base64_encode($user['user_password'] ^ $backlink['backlink_started']);
		$eol = "\n";
		$headers = 'From: Todo system administrator<valdas@enigmasoftware.com>'.$eol;
		$headers .= "Message-ID: <".$now." TheSystem@enigmasoftware.com>".$eol;
		$headers .= "X-Mailer: PHP v".phpversion().$eol;          
		$mime_boundary = md5(time());
		$headers .= 'MIME-Version: 1.0'.$eol;
		$headers .= "Content-Type: multipart/alternative; boundary=\"".$mime_boundary."\"".$eol.$eol;
		$msg = "";
		# Text Version
		$msg .= "--".$mime_boundary.$eol;
		$msg .= "Content-Type: text/plain; charset=iso-8859-1".$eol;
		$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
		$msg .= "Update mail client to see more information".$eol;
		$msg .= "backlink url localhost/todo/index.php?module=backlinks&action=view&backlink_id=".$backlink['backlink_id']."&dologin=$dologin".$eol.$eol;
		# HTML Version
		$msg .= "--".$mime_boundary.$eol;
		$msg .= "Content-Type: text/html; charset=iso-8859-1".$eol;
		$msg .= "Content-Transfer-Encoding: 8bit".$eol.$eol;
		$msg .= "<b>Project: </b>$backlink[project_url]<br />".$eol;
		$msg .= "<b>Added on: </b>$backlink[backlink_started]<br />".$eol;
		$msg .= "<b>backlink: </b>".nl2br(stripcslashes($backlink['backlink_description']))."<br />".$eol;
		$msg .= "<b>Notes: </b>".nl2br(stripcslashes($backlink['backlink_comments']))."<br />".$eol;
		$msg .= "<b>backlink Details: </b><a href='localhost/todo/index.php?module=backlinks&action=view&backlink_id=".$backlink['backlink_id']."&dologin=$dologin'>localhost/todo/index.php?module=backlinks&action=view&backlink_id=".$backlink['backlink_id']."</a>".$eol.$eol;
		$msg .= "--".$mime_boundary."--".$eol;
		mail($email, $this->backlink_title, $msg, $headers);
	}    
	
	public function getBacklinks() {
		
		$sql = "SELECT bl_info_id, bl_name, bl_url FROM t_backlink_info";
		$data2 = $this->_db->getAll($sql);
	}

	public function editbacklink() {
		
	    ZNF_Util_Utility :: addAllSlashes($_POST);
	    
		//page rank
    	$PRDAO = new PR_Business_BacklinksDAO();		
		$PR =$PRDAO->getPageRank($_POST['bl_url']);


        //
        $domain = new Links_Business_BacklinksDAO();
        $domain = $domain->getDomain($_POST['bl_url']);

		if($_POST['cost']){
		$sql = "UPDATE t_backlink_costs SET  
			from_date        = '$_POST[from_date]',
			to_date          = '$_POST[to_date]',
			cost             = '$_POST[cost]',
			currency         = '$_POST[currency]', 
			type             = '$_POST[type]',
			reciprocal_url   = '$_POST[reciprocal_url]' 
			WHERE bl_cost_id = '$_POST[bl_cost_id]'
			";
		
		$this->_db->query($sql);
		}
		
		$sql = "UPDATE t_backlink_info SET
				bl_url		= '$_POST[bl_url]',
				bl_name 	= '$domain',					
				last_check_date = NOW(),
				PR 			= '$PR'
					WHERE bl_info_id = '$_POST[backlink_id]' 
					";
		 
		$this->_db->query($sql);
			
			$sql =  "UPDATE t_backlinks SET
			bl_info_id  = '$_POST[backlink_id]',
			cost_id 	= '$_POST[bl_cost_id]',
			bl_type_id  = '$_POST[bl_type_id]',
			bl_lng_id   = '$_POST[bl_lng_id]',
			project_id  = '$_POST[project_id]',
			user_id		= '$_GET[user_id]'
				WHERE bl_id = $_POST[backlink_id]";	
			
			
		$this->_db->query($sql);
	}
    
	public function updatebacklink($backlink_id, $backlink_url, $backlink_comments) {
		$backlink_comments = addslashes($backlink_comments);
		$sql = "UPDATE t_backlinks SET backlink_url = '$backlink_url', backlink_comments = '$backlink_comments' WHERE backlink_id = $backlink_id";
		$this->_db->query($sql);
	}

	public function setbacklinkActive($backlink_id) {
		$sql = "UPDATE t_backlinks SET backlink_state = 1 WHERE backlink_id = $backlink_id";
		$this->_db->query($sql);
	}
	
	public function setbacklinkTaken($backlink_id, $user_id) {
		$sql = "UPDATE t_backlinks SET user_id = $user_id WHERE backlink_id = $backlink_id";
		$this->_db->query($sql);
	}
	
	public function closebacklink($backlink_id) {
		$sql = "UPDATE t_backlinks SET backlink_state = 0, bl_id = 0, backlink_finished = NOW() WHERE backlink_id = $backlink_id";
		$this->_db->query($sql);
	}

	public function undonebacklink($backlink_id) {
		$sql = "UPDATE t_backlinks SET bl_id = 1, backlink_finished = '0000-00-00 00:00:00' WHERE backlink_id = $backlink_id";
		$this->_db->query($sql);
	}

	public function detailsbacklink($backlink_id, $backlink_url, $backlink_comments) {
		$backlink_comments = addslashes($backlink_comments);
		$sql = "UPDATE t_backlinks SET backlink_state = 3, backlink_url = '$backlink_url', backlink_comments = '$backlink_comments' WHERE backlink_id = $backlink_id";
		$this->_db->query($sql);
	}

	public function answerbacklink($backlink_id, $backlink_url, $backlink_comments) {
		$backlink_comments = addslashes($backlink_comments);
		$sql = "UPDATE t_backlinks SET backlink_state = 0, backlink_url = '$backlink_url', backlink_comments = '$backlink_comments' WHERE backlink_id = $backlink_id";
		$this->_db->query($sql);
	}
	
	
	public function rescanLinks($links) {

		foreach($links as $link){

				$backlink = $this->scanBacklink($link['bl_url']);
				
				$sql = "UPDATE t_backlink_info SET
						bl_name = '$backlink->bl_name',				
						last_check_date = NOW(),
						PR = '$backlink->PR',
						flag = '$backlink->flag', 
						OBL = '$backlink->OBL' 		 
							WHERE bl_info_id = '$link[bl_info_id]'";
				 
				$this->_db->query($sql);
							
		//--- t_backlinks_info

		$sql = "UPDATE t_backlink_cache_history SET 
					google_date = '$backlink->GoogleCacheDate',
					yahoo_date = '$backlink->YahooCacheDate',
					msn_date = '$backlink->MsnCacheDate'
						WHERE  bl_cache_id = $link[bl_info_id]";
					
				$this->_db->query($sql);
			}
	}

	public function scanBacklink($url, $reciprocal_url )
	{
		$link = new Links_Business_BacklinksDAO();
        $backlink->domain = $link->getDomain($url);		
        
        /*
        //<---
		$backlink->GoogleCacheDate= date('y-m-d h:M');
		$backlink->YahooCacheDate= date('y-m-d h:M');

		$backlink->flag = "OK";
		$backlink->OBL = 1;
		$backlink->PR = 2;
		//-->
		
		return $backlink; 
			
	*/
        
		$curl = new CCurl();
		
		set_time_limit(29);
		$backlink->GoogleCacheDate = $curl->getGoogleCachedDate($url);							//		echo $GoogleCacheDate;
		$backlink->YahooCacheDate = $curl->getYahooCachedDate($url);							//		echo $GoogleCacheDate;
		$backlink->MsnCacheDate = $curl->getMSNCachedDate($url);

		$siteSource = $curl->get($url);
		
		$metaRobotsPatern = '|name[\s]*=[\s]*[\'"][\s]*robots[\s]*[\'"].*nofollow|';
		
		$nofollow = preg_match($metaRobotsPatern, $siteSource, $matches);

		// 	clean up tabs and new lines
		$siteSource = preg_replace("/\s\s+|\t\t+|\n\r+|\n\n+|\r\r+/","",$siteSource);
				
		//flag 
		if($nofollow){
			$backlink->flag = 'nofollow';
		}
		
		$backlink->flag = $curl->checkBacklink($reciprocal_url, $siteSource, $backlink->bl_name);
		
		// comments
		$siteSource = preg_replace(  '|<!--[^\-]+-->|', '', $siteSource);
		
		//iframe
		$siteSource = preg_replace(  '|<iframe[^\-]+iframe>|', '', $siteSource);
		
		//jscript
		$siteSource = preg_replace(  '|<script [^\-]+script>|', '', $siteSource);
		


		//page rank
    	$PRDAO = new PR_Business_BacklinksDAO();		
		$backlink->PR = $PRDAO->getPageRank($url);
				
        //Outbound Links		
		$backlink->OBL = $link->getOBL($siteSource, $backlink->domain);          				//echo $OBL; 
		
		return $backlink;
	}		
	
	public function __destruct() {
	}


}




class backlinks_Business_backlinksDAOException extends Exception
{
}



?>


